<?php
namespace backend\controllers;

use common\models\SupplierAttribute;
use common\models\SupplierAttributeValue;
use common\service\ConstantService;

class SupplierAttributeController extends BaseController
{
    /**
     * 新增属性名称
     */
    public function actionAddAttribute(){
        if($this->isAjax() && $this->isAjax()){
            $name = $this->post('name');
            //查询 如果有就直接返回 ,没有就新增
            $row = SupplierAttribute::find()
                ->where(['attribute_name'=>$name])
                ->asArray()->one();
            $ret = [];
            if(!empty($row)){
                //获取属性值
                $list = SupplierAttributeValue::find()->where(['attr_id'=>$row['id']])->asArray()->all();
                $ret['list'] = $list;
                $ret['row']  = $row;
            }else{
                //新增
                $attribute_model = new SupplierAttribute();
                $data['attribute_name'] = $name;
                $data['is_del'] = 0;
                $data['create_time'] = time();
                $data['update_time'] = time();
                $attribute_model->setAttributes($data);
                if($attribute_model->save(0)){
                    $ret['row'] = $attribute_model->toArray();
                    $ret['list'] = [];
                }else{
                    return $this->renderJson([],'保存失败',ConstantService::$response_fail);
                }
            }
            return $this->renderJson($ret,'添加成功',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 新增属性值
     */
    public function actionAddAttrData(){
        if($this->isAjax() && $this->isPost()){

            $id = $this->post('id');
            $name = $this->post('name');
            $value = $this->post('value');

            if(empty($id) || empty($name) || empty($value)){
                return $this->renderJson([],'参数错误',ConstantService::$response_fail);
            }
            // 这里需要查询 如果有同名则不能在添加了
            $row = SupplierAttributeValue::find()->where(['attr_name'=>$name,'value'=>$value,'attr_id'=>$id])->asArray()->one();
            if(!empty($row)){
                return $this->renderJson([],'已经存在同名的属性',ConstantService::$response_fail);
            }
            $attr_value_model = new SupplierAttributeValue();
            $data['attr_name'] = $name;
            $data['attr_id'] = $id;
            $data['value'] = $value;
            $data['create_time'] = time();
            $data['update_time'] = time();
            $attr_value_model->setAttributes($data);
            $attr_value_model->save();
            $row = $attr_value_model->toArray();

            return $this->renderJson($row,'保存成功',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }
}